<template>
  <div class="template-wrapper">
    <el-select
      ref="select"
      v-model="selectedValue"
      filterable
      remote
      reserve-keyword
      :placeholder="placeholder"
      :remote-method="handleSearch"
      :loading="loading"
      :disabled="disabled"
      :clearable="clearable"
      @visible-change="handleDropdownVisible"
      @change="handleChange"
      @clear="handleClear"
      style="width: 100%"
    >
      <el-option
        v-for="item in options"
        :key="item.pointId"
        :label="item.name"
        :value="item.pointId"
      >
        <div class="option-item">
          <span>{{ item.name }}</span>
        </div>
      </el-option>
      <div v-if="hasMore" class="load-more" @click="loadMore">
        {{ loading ? '加载中...' : '点击加载更多' }}
      </div>
    </el-select>
  </div>
</template>

<script>
import { listPoints } from "@/api/question/know";

export default {
  name: "InputAndSearchWithList",
  props: {
    value: {
      type: [String, Number],
      default: ''
    },
    categoryId: {
      type: [String, Number],
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: '请输入知识点名称'
    }
  },
  data() {
    return {
      selectedValue: this.value,
      loading: false,
      options: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        categoryId: this.categoryId
      },
      total: 0,
      timer: null,
      isInitialized: false,
      initialValueSet: false
    };
  },
  computed: {
    hasMore() {
      return this.options.length < this.total;
    }
  },
  methods: {
    async handleSearch(query) {
      if (this.timer) clearTimeout(this.timer);

      this.timer = setTimeout(async () => {
        this.queryParams = {
          ...this.queryParams,
          pageNum: 1,
          name: query || undefined
        };
        await this.loadData();
      }, 300);
    },

    async loadData() {
      try {
        this.loading = true;
        const res = await listPoints(this.queryParams);
        if (res.code === 200) {
          this.options = this.queryParams.pageNum === 1
            ? res.rows
            : [...this.options, ...res.rows];
          this.total = res.total;
          this.isInitialized = true;

          // 数据加载完成后，尝试设置当前选中的值
          if (this.selectedValue && !this.initialValueSet) {
            await this.setCurrentValue(this.selectedValue);
            this.initialValueSet = true;
          }
        }
      } finally {
        this.loading = false;
      }
    },

    async loadMore() {
      if (!this.hasMore || this.loading) return;
      this.queryParams.pageNum++;
      await this.loadData();
    },

    handleChange(value) {
      const selectedOption = this.options.find(item => item.pointId === value);
      this.$emit("input", value);
      this.$emit("change", value, selectedOption);

      // 手动更新select的显示文本
      this.$nextTick(() => {
        if (this.$refs.select) {
          this.$refs.select.selectedLabel = selectedOption?.name || '';
        }
      });
    },

    handleClear() {
      this.selectedValue = '';
      this.$emit("input", '');
      this.$emit("change", null);
    },

    handleDropdownVisible(visible) {
      if (visible && !this.isInitialized) {
        this.loadData();
      }
    },

    async refreshData() {
      this.queryParams.pageNum = 1;
      await this.loadData();
    },

    async setCurrentValue(value) {
      this.selectedValue = value;

      if (!value) return;

      // 1. 先在现有选项中查找
      const existingOption = this.options.find(item => item.pointId === value);
      if (existingOption) {
        this.updateSelectDisplay(existingOption.name);
        return;
      }

      // 2. 如果选项中没有，则单独查询该知识点
      try {
        const res = await listPoints({
          pointId: value,
          pageNum: 1,
          pageSize: 1
        });

        if (res.code === 200 && res.rows.length > 0) {
          const point = res.rows[0];
          // 添加到选项列表
          if (!this.options.some(item => item.pointId === point.pointId)) {
            this.options.unshift(point);
            this.total++;
          }
          this.updateSelectDisplay(point.name);
        }
      } catch (error) {
        console.error('获取知识点失败:', error);
      }
    },

    updateSelectDisplay(label) {
      this.$nextTick(() => {
        if (this.$refs.select) {
          this.$refs.select.selectedLabel = label || '';
        }
      });
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(newVal) {
        if (newVal !== this.selectedValue) {
          this.selectedValue = newVal;
          if (newVal && this.isInitialized) {
            this.setCurrentValue(newVal);
          }
        }
      }
    },
    categoryId: {
      immediate: true,
      async handler(newVal) {
        this.queryParams.categoryId = newVal;
        this.queryParams.pageNum = 1;
        await this.loadData();
      }
    }
  },
  mounted() {
    // 初始加载
    if (this.value) {
      this.loadData();
    }
  }
};
</script>

<style scoped lang="scss">
.template-wrapper {
  ::v-deep .el-select-dropdown__item {
    display: flex;
    justify-content: space-between;
    padding: 8px 15px;

    .option-item {
      display: flex;
      align-items: center;
      width: 100%;
    }
  }

  .load-more {
    text-align: center;
    padding: 8px 0;
    color: #909399;
    cursor: pointer;
    font-size: 12px;

    &:hover {
      background-color: #f5f7fa;
    }
  }
}
</style>
